/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.guide.web;



import com.jeeplus.common.web.Result;
import com.jeeplus.modules.guide.model.query.ModAppointment;
import com.jeeplus.modules.guide.model.vo.ModAppointmentOut;
import com.jeeplus.modules.guide.model.vo.ServiceTime;
import com.jeeplus.modules.guide.service.*;
import com.jeeplus.modules.guide.utils.AESEncryptionUtils;
import io.lettuce.core.dynamic.annotation.Param;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;


/*
蓉易办对接排队叫号
*/
@RestController
@Api(tags = "蓉易办")
@RequestMapping("/RongYiBanAppointmentContriller")
@RequiredArgsConstructor
public class RongYiBanAppointmentContriller {
    //私钥
    @Value("${GETLEVEL_KEY}")
    private String GETLEVEL_KEY;
    @Value("${ISAPPOINTMENT_KEY}")
    private String ISAPPOINTMENT_KEY;
    @Value("${APPOINTMENTTIME_KEY}")
    private String APPOINTMENTTIME_KEY;
    @Value("${APPOINTMENTINFOUP_KEY}")
    private String APPOINTMENTINFOUP_KEY;
    @Value("${DELAPPOINTMENT_KEY}")
    private String DELAPPOINTMENT_KEY;

    @Value("${ALGORITHMSTR}")
    private String ALGORITHMSTR;
    private final RongYiBanService rongYiBanService;
    private final VersionService versionService;
    private final RongYiBanAppointmentService rongYiBanAppointmentService;
    private final AppointmentService appointmentService;
	private static final Logger log = LoggerFactory.getLogger(RongYiBanAppointmentContriller.class);


    /**
     * 蓉易办-预约对接-获取预约层级
     */
    @ApiOperation(value ="蓉易办-预约对接-获取预约层级")
    @PostMapping(value = "getLevel")
    public String getLevel(HttpServletRequest request){
        log.error("蓉易办-预约对接-获取预约层级");
        String string="";
        //把数据提取和解密
        String dataAndDecode = getDataAndDecode(request,GETLEVEL_KEY);
        JSONObject data = JSONObject.fromObject(dataAndDecode);
        String levelid=data.getString("levelid");//预约层级ID",
        List<Map<String, String>> level =new ArrayList<>();
        if ("0".equals(levelid)){
            level = rongYiBanService.getLevel("510109000000");
        }else {
            level =rongYiBanService.getBusiness(levelid);
        }
        JSONArray jsonArray = JSONArray.fromObject(level);
        string="{\"custom\":{\"code\":1,\"levellist\":"+jsonArray+",\"text\":\"\"},\"status\":{ \"code\":1,\"text\":\"\" }}";
        try {
            string = AESEncryptionUtils.aesEncrypt(string, GETLEVEL_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("result",string);
        log.error(jsonObject.toString());
        return jsonObject.toString();
    }
    /**
     * 蓉易办-预约对接-是否可预约
     */
    @PostMapping(value = "isAppointment")
    @ApiOperation(value ="蓉易办-预约对接-是否可预约")
    public String isAppointment(HttpServletRequest request){
        log.error("蓉易办-预约对接-是否可预约");
        String string="";
        //把数据提取和解密
        String dataAndDecode = getDataAndDecode(request,ISAPPOINTMENT_KEY);
        JSONObject data = JSONObject.fromObject(dataAndDecode);
       String appointdate=data.getString("appointdate");//预约日期",
       String itemid=data.getString("itemid");//事项实施编码",
       String accountidcard=data.getString("accountidcard");//用户身份证"
        Map<String, String> serialById = rongYiBanService.getSerialById(itemid);
        if(!"".equals(serialById.get("businessName")) && null !=serialById.get("businessName")){
            List<ServiceTime> serviceTime = appointmentService.getServiceTime(serialById.get("areaId"), serialById.get("businessid"));
                serialById.put("appointdate",appointdate);
                serialById.put("accountidcard",accountidcard);
                int appointment = rongYiBanService.isAppointment(serialById);
            if(appointment==0) {
                boolean isTrue=false;
                for (int i = 0; i < serviceTime.size(); i++) {
                    if (appointdate.equals(serviceTime.get(i).getTime())){
                       isTrue=true;
                    }
                }
                if (isTrue){
                    string="{" +
                            "    \"custom\":{" +
                            "        \"code\":200," +
                            "        \"appointresult\":\"1\"," +
                            "        \"text\":\"可预约\"" +
                            "    }," +
                            "    \"status\":{" +
                            "        \"code\":1," +
                            "        \"text\":\"\"" +
                            "    }" +
                            "}";
                }else{
                    string="{" +
                            "    \"custom\":{" +
                            "        \"code\":200," +
                            "        \"appointresult\":\"0\"," +
                            "        \"text\":\"请选择近十天的法定工作日时间\"" +
                            "    }," +
                            "    \"status\":{" +
                            "        \"code\":1," +
                            "        \"text\":\"\"" +
                            "    }" +
                            "}";
                }

            }else {
                string="{" +
                        "    \"custom\":{" +
                        "        \"code\":200," +
                        "        \"appointresult\":\"0\"," +
                        "        \"text\":\"该身份证当天已有预约\"" +
                        "    }," +
                        "    \"status\":{" +
                        "        \"code\":1," +
                        "        \"text\":\"\"" +
                        "    }" +
                        "}";
            }
        }else {
           //返回未找到改事项
             string="{" +
                    "    \"custom\":{" +
                    "        \"code\":200," +
                    "        \"appointresult\":\"0\"," +
                    "        \"text\":\"未找到该业务\"" +
                    "    }," +
                    "    \"status\":{" +
                    "        \"code\":1," +
                    "        \"text\":\"\"" +
                    "    }" +
                    "}";
        }
        JSONObject jsonObject1 = JSONObject.fromObject(string);
        try {
            string = AESEncryptionUtils.aesEncrypt(jsonObject1.toString(), ISAPPOINTMENT_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("result",string);
        log.error(jsonObject.toString());
        return jsonObject.toString();
    }

    /**
     * 蓉易办-预约对接-获取具体事项预约时间段
     */
    @PostMapping(value = "appointmentTime")
    @ApiOperation(value ="蓉易办-预约对接-获取具体事项预约时间段")
    public String appointmentTime(HttpServletRequest request){
        log.error("蓉易办-预约对接-获取具体事项预约时间段");
        String string="";
        //把数据提取和解密
        String dataAndDecode = getDataAndDecode(request,APPOINTMENTTIME_KEY);
        JSONObject data = JSONObject.fromObject(dataAndDecode);
       String appointdate=data.getString("appointdate");//预约日期",
       String itemid=data.getString("itemid");//事项实施编码",
       String accountidcard=data.getString("accountidcard");//用户身份证"
        Map<String, String> serialById = rongYiBanService.getSerialById(itemid);
        if(!"".equals(serialById.get("businessName")) && null !=serialById.get("businessName")){
            List<ServiceTime> serviceTime = appointmentService.getServiceTime(serialById.get("areaId"), serialById.get("businessid"));
            Map<String, Object> quHao = rongYiBanService.isQuHao(accountidcard,itemid,appointdate);
            boolean isTrue=false;
            JSONArray jsonArray =null;
            for (int i = 0; i < serviceTime.size(); i++) {
                    if (appointdate.equals(serviceTime.get(i).getTime())){
                        List<ServiceTime.Detail> details = serviceTime.get(i).getDetails();
                        List<Map<String,Object>> list=new ArrayList<>();
                        for (int k = 0; k < details.size(); k++) {
                            Map<String,Object> map=new HashMap<>();
                            String[] split = details.get(k).getTimePeriodStr().split("-");
                            map.put("appointtimeend",split[1]);
                            map.put("appointmaxsum",details.get(k).getQuota());
                            map.put("isappoint","0");
                            map.put("appointguid","");
                            map.put("appointsum",5-details.get(k).getQuota());
                            map.put("appointtimestart",split[0]);
                           if(null != quHao && !"".equals(quHao)){
                               if(split[0].equals( quHao.get("number")+":00")){
                                   map.put("appointguid",quHao.get("id"));
                               }
                           }


                            list.add(map);
                        }
                         jsonArray = JSONArray.fromObject(list);
                        String s ="";
                        try {
                            s = AESEncryptionUtils.aesEncrypt(list.toString(), APPOINTMENTTIME_KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        isTrue=true;
                    }
                }
            if(isTrue){
                string="{" +
                        "    \"custom\":{" +
                        "        \"appointtimelist\":"+jsonArray+"," +
                        "        \"code\":200," +
                        "        \"text\":\"成功\"" +
                        "    }," +
                        "    \"status\":{" +
                        "        \"code\":1," +
                        "        \"text\":\"\"" +
                        "    }" +
                        "}";
                System.out.println(string);
            }else{
                string="{" +
                        "    \"custom\":{" +
                        "        \"code\":200," +
                        "        \"text\":\"请选择近十天的法定工作日时间\"" +
                        "    }," +
                        "    \"status\":{" +
                        "        \"code\":0," +
                        "        \"text\":\"\"" +
                        "    }" +
                        "}";
            }

        }else {
            //返回未找到改事项
            string="{" +
                    "    \"custom\":{" +
                    "        \"code\":200," +
                    "        \"text\":\"未找到该业务\"" +
                    "    }," +
                    "    \"status\":{" +
                    "        \"code\":0," +
                    "        \"text\":\"\"" +
                    "    }" +
                    "}";


        }
        JSONObject jsonObject1 = JSONObject.fromObject(string);
        try {
            string = AESEncryptionUtils.aesEncrypt(jsonObject1.toString(), APPOINTMENTTIME_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("result",string);
        log.error(jsonObject.toString());
        return jsonObject.toString();
    }


    /**
     * 蓉易办-预约对接-预约信息上传
     */
    @PostMapping(value = "appointmentInfoUp")
    @ApiOperation(value ="蓉易办-预约对接-预约信息上传")
    public String appointmentInfoUp(HttpServletRequest request){
        log.error("蓉易办-预约对接-预约信息上传");
        String string="";
        //把数据提取和解密
        String dataAndDecode = getDataAndDecode(request,APPOINTMENTINFOUP_KEY);
        JSONObject data = JSONObject.fromObject(dataAndDecode);
        String appointdate=data.getString("appointdate");//预约日期",
        String itemid=data.getString("itemid");//事项实施编码",
        String appointtimestart=data.getString("appointtimestart");//预约开始时间"
        String appointtimeend=data.getString("appointtimeend");//预约结束时间"
        String appointtype=data.getString("appointtype");//预约来源"
        String username=data.getString("username");//姓名"
        String accountidcard=data.getString("identitycardid");//用户身份证"
        String mobile=data.getString("mobile");//手机号"
        Map<String, String> serialById = rongYiBanService.getSerialById(itemid);
        if(!"".equals(serialById.get("businessName")) && null !=serialById.get("businessName")){
                ModAppointment mt = new ModAppointment();
                mt.setBusinessId(itemid);
                mt.setSysNo(serialById.get("areaId"));
                mt.setTime(appointdate);
                String[] split = appointtimestart.split(":");
                int i = Integer.parseInt(split[0]);
                mt.setTimePeriod(i);
                mt.setSysName(appointtype+"(蓉易办)");
                Result<ModAppointmentOut> result = appointmentService.saveAppointment(mt, true, accountidcard, mobile, username);
                if (result.getResp_code() == HttpStatus.OK.value()) {
                    Map<String,String> map=new HashMap<>();
                    map.put("areaId",serialById.get("areaId"));
                    map.put("accountidcard",accountidcard);
                    map.put("businessid",serialById.get("businessid"));
                    map.put("appointdate",appointdate);
                    String appointmentId = rongYiBanService.getAppointmentId(map);
//                    return AjaxJson.success("预约成功");
                    string="{" +
                            "    \"custom\":{" +
                            "        \"code\":200," +
                            "        \"result\":\"1\"," +
                            "\"appointguid\":\""+appointmentId+"\"," +
                            "        \"text\":\"\"" +
                            "    }," +
                            "    \"status\":{" +
                            "        \"code\":1," +
                            "        \"text\":\"预约成功\"" +
                            "    }" +
                            "}";
                } else {
                    string="{" +
                            "    \"custom\":{" +
                            "        \"code\":300," +
                            "        \"result\":\"0\"," +
                            "\"appointguid\":\"\"," +
                            "        \"text\":\""+result.getResp_msg()+"\"" +
                            "    }," +
                            "    \"status\":{" +
                            "        \"code\":1," +
                            "        \"text\":\"\"" +
                            "    }" +
                            "}";
                }
            }else{
                string="{" +
                        "    \"custom\":{" +
                        "        \"code\":300," +
                        "        \"result\":\"0\"," +
                        "\"appointguid\":\"\"," +
                        "        \"text\":\"未找到该业务\"" +
                        "    }," +
                        "    \"status\":{" +
                        "        \"code\":1," +
                        "        \"text\":\"\"" +
                        "    }" +
                        "}";
            }

        JSONObject jsonObject1 = JSONObject.fromObject(string);
        try {
            string = AESEncryptionUtils.aesEncrypt(jsonObject1.toString(), APPOINTMENTINFOUP_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("result",string);
        log.error(jsonObject.toString());
        return jsonObject.toString();
    }

    /**
     * 蓉易办-预约对接-删除预约
     */
    @PostMapping(value = "delAppointment")
    @ApiOperation(value ="蓉易办-预约对接-预约删除")
    public String delAppointment(HttpServletRequest request){
        log.error("蓉易办-预约对接-预约删除");
        //把数据提取和解密
        String dataAndDecode = getDataAndDecode(request,DELAPPOINTMENT_KEY);
        JSONObject data = JSONObject.fromObject(dataAndDecode);
       String appointguid=data.getString("appointguid");//预约ID",
//        String appointguid="1dab0594-6cc9-43e4-b372-71124bbb157d";//预约ID"
        rongYiBanService.delAppointment(appointguid);
//        log.error(data);
       String string= "   { \"custom\":{" +
                "        \"code\":200," +
                "        \"result\":\"1\"," +
                "        \"text\":\"删除成功\"" +
                "    },\n" +
                "    \"status\":{" +
                "        \"code\":1," +
                "        \"text\":\"\"" +
                "    }\n" +
                "}";
        JSONObject jsonObject1 = JSONObject.fromObject(string);
        try {
            string = AESEncryptionUtils.aesEncrypt(jsonObject1.toString(), DELAPPOINTMENT_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("result",string);
        log.error(jsonObject.toString());
        return jsonObject.toString();
    }
    /**
     * 数据提取和解密
     * @param request
     * @return
     */
    public String getDataAndDecode(HttpServletRequest request,String KEY){
        String str, body = "";
        try{
            BufferedReader reader = request.getReader();
            while((str = reader.readLine()) != null){
                body += str;
            }
            reader.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        log.error(body);
        String data = JSONObject.fromObject(body).getString("data");
        String s="";
        try {
            s = AESEncryptionUtils.aesDecrypt(data, KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }




    /**
     * 市医保-预约对接-业务事项查询接口
     */
    @PostMapping(value = "getYBJBusiness")
    public  Map<String, Object> getYBJBusiness(String appid,String aaz001,String itemCode){
        Map<String,Object> mapReturn = new HashedMap();
        mapReturn.put("appid",appid);
        mapReturn.put("aaz001",aaz001);
        mapReturn.put("message", "200-请求成功");
        List<Map<String, Object>> zoning = rongYiBanService.getZoning();
        for (int i = 0; i < zoning.size(); i++) {
            Map<String, Object> map = zoning.get(i);
            if("510109000000".equals(map.get("orgrizeId").toString())){
                map.put("list",rongYiBanService.getDepartment());
            }else{
                map.put("list",rongYiBanService.getBusinessByZoning(map.get("orgrizeId").toString()));
            }
        }
        mapReturn.put("data",zoning);

        return mapReturn;
    }
    /**
     * 市医保-预约对接-可预约排号日期查询接口
     */
    @PostMapping(value = "getYBJAppointmentDay")
    public Map<String,Object> getYBJAppointmentDay(String appid,String aaz001,String itemCode){
        Map<String,Object> map = new HashedMap();
        map.put("appid",appid);
        map.put("aaz001",aaz001);
        map.put("aaz002", UUID.randomUUID().toString());
        Map<String, String> serialById = rongYiBanService.getSerialById(itemCode);
        if (null!= serialById && !serialById.isEmpty()) {
            map.put("message", "200-请求成功");
            List<ServiceTime> serviceTime = appointmentService.getServiceTime(serialById.get("areaId"), serialById.get("businessid"));
            List<String> day=new ArrayList<>();
            for (int i = 0; i < serviceTime.size(); i++) {
                day.add(serviceTime.get(i).getTime().replace("-", ""));
            }
            map.put("list",day);
        }else {
            map.put("message", "201-参数错误");
        }

        return map;
    }
    /**
     * 市医保-预约对接-可预约时间段查询接口
     */
    @PostMapping(value = "getYBJAppointmentTime")
    public Map<String,Object> getYBJAppointmentTime(String appid,String aaz001,String itemCode,String day){
        Map<String,Object> map = new HashedMap();
        map.put("appid",appid);
        map.put("aaz001",aaz001);
        map.put("aaz002", UUID.randomUUID().toString());
        Map<String, String> serialById = rongYiBanService.getSerialById(itemCode);
        if (null!= serialById && !serialById.isEmpty()) {
            map.put("message", "200-请求成功");
            List<ServiceTime> serviceTime = appointmentService.getServiceTime(serialById.get("areaId"), serialById.get("businessid"));
            List<Map<String,Object>> dayTime=new ArrayList<>();
            for (int i = 0; i < serviceTime.size(); i++) {
                if (serviceTime.get(i).getTime().replace("-", "").equals(day)){
                    List<ServiceTime.Detail> details = serviceTime.get(i).getDetails();
                    for (int k = 0; k < details.size(); k++) {
                        Map<String,Object> stringMap=new HashMap<>();
                        String[] split = details.get(k).getTimePeriodStr().split("-");
                        stringMap.put("timeStart",split[0]);
                        stringMap.put("timeEnd",split[1]);
                        stringMap.put("allowNum",details.get(k).getQuota());
                        dayTime.add(stringMap);
                    }
                }

            }
            map.put("list",dayTime);
        }else {
            map.put("message", "201-参数错误");
        }

        return map;
    }
    /**
     * 市医保-预约对接-政务预约排号接口
     */
    @PostMapping(value = "insertYBJAppointmentInfo")
    public Map<String,Object> insertYBJAppointmentInfo(String appid,String aaz001,String aac002,String aac003,String phone,String itemCode,String day,String timeStart,String timeEnd){
        Map<String,Object> map = new HashedMap();
        map.put("appid",appid);
        map.put("aaz001",aaz001);
        map.put("aaz002", UUID.randomUUID().toString());
        Map<String, String> serialById = rongYiBanService.getSerialById(itemCode);
        if(!"".equals(serialById.get("businessName")) && null !=serialById.get("businessName")){
            ModAppointment mt = new ModAppointment();
            mt.setBusinessId(itemCode);
            mt.setSysNo(serialById.get("areaId"));
            StringBuilder sb = new StringBuilder(day);
            sb.insert(4,"-");
            sb.insert(7,"-");
            mt.setTime(sb.toString());
            String[] split = timeStart.split(":");
            int i = Integer.parseInt(split[0]);
            mt.setTimePeriod(i);
            mt.setSysName("市医保");
            Result<ModAppointmentOut> result = appointmentService.saveAppointment(mt, true, aac002, phone, aac003);
            if (result.getResp_code() == HttpStatus.OK.value()){
                map.put("message", "200-请求成功");
                map.put("data", "{\"isSuccess\":\"1\"}");
            }else{
                map.put("message", "200-请求成功");
                map.put("data", "{\"isSuccess\":\"0\","+result.getResp_msg()+"}");
            }
        }else{
            map.put("message", "201-参数错误");
        }
        return map;
    }
    /**
     * 市医保-预约对接-当前预约排号查询接口
     */
    @PostMapping(value = "getYBJAppointmentInfoNew")
    public Map<String,Object> getYBJAppointmentInfoNew(String appid,String aaz001,String aac002,String isTakeNum){
        Map<String,Object> map = new HashedMap();
        map.put("appid",appid);
        map.put("aaz001",aaz001);
        map.put("aaz002", UUID.randomUUID().toString());
        List<Map<String, String>> ybjyy = rongYiBanService.getYBJYY(aac002, isTakeNum);
        if (ybjyy.size()!=0) {
            map.put("message", "200-请求成功");
            map.put("list",ybjyy);
        }else{
            map.put("message", "201-参数错误");
        }
        return map;
    }
    /**
     * 市医保-预约对接-当预约排号历史查询接口
     */
    @PostMapping(value = "getYBJAppointmentInfoHistory")
    public Map<String,Object> getYBJAppointmentInfoHistory(String appid,String aaz001,String aac002,String isTakeNum,String isHandle,String pageIndex,String pageSize){
        Map<String,Object> map = new HashedMap();
        map.put("appid",appid);
        map.put("aaz001",aaz001);
        map.put("aaz002", UUID.randomUUID().toString());
        List<Map<String, String>> ybjAppointmentInfoHistory = rongYiBanService.getYBJAppointmentInfoHistory(aac002, isTakeNum, isHandle, pageIndex, pageSize);
        for (int i = 0; i < ybjAppointmentInfoHistory.size(); i++) {
            ybjAppointmentInfoHistory.get(i).put("day",ybjAppointmentInfoHistory.get(i).get("dayTime"));
            ybjAppointmentInfoHistory.get(i).remove("dayTime");
        }
        if(ybjAppointmentInfoHistory.size()!=0){
            map.put("message", "200-请求成功");
            map.put("list",ybjAppointmentInfoHistory);
        }else{
            map.put("message", "201-参数错误");
        }
        return map;
    }
}
